package cn.iocoder.yudao.module.engine.service.core.timer;

import cn.iocoder.yudao.module.engine.model.config.EngineConfig;
import cn.iocoder.yudao.module.engine.model.context.EngineSessionContext;
import cn.iocoder.yudao.module.engine.service.conn.IEngineConnectListener;
import cn.iocoder.yudao.module.infra.utils.EngineExecutorUtils;
import io.netty.util.HashedWheelTimer;
import io.netty.util.concurrent.DefaultThreadFactory;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

@Service
public class EngineTimerManager implements IEngineConnectListener {
    private ExecutorService timerExecutors;

    private final HashedWheelTimer wheelTimer = new HashedWheelTimer(new DefaultThreadFactory("engine-timer-wheel"), 1, TimeUnit.SECONDS);

    @Autowired
    private List<IEngineTimerService> timerServices;
    @Resource
    private EngineConfig engineConfig;

    @PostConstruct
    public void init() {
        final EngineConfig.ThreadPool threadPool = engineConfig.getThreadPool();
        timerExecutors = EngineExecutorUtils.newThreadPoolExecutor(
                threadPool.getEngineTimerCorePoolSize(),
                "engine-timer-work"
        );
    }

    @Override
    public void onConnected(EngineSessionContext sessionContext) {
        timerServices.forEach(service ->
                service.addTimerTask(wheelTimer, sessionContext, timerExecutors)
        );
    }

    @Override
    public void onDisconnected(EngineSessionContext sessionContext) {
        timerServices.forEach(service ->
                service.cancelTimerTask(wheelTimer, sessionContext, timerExecutors)
        );
    }
}
